package bootstrap

import (
	"cloud-navigation/global"
	"cloud-navigation/route"
	"cloud-navigation/utils"
	"net/http"
	"net/http/httputil"
	"net/url"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

// 创建路由
func setupRouter() *gin.Engine {
	router := gin.New()
	router.Use(gin.Logger())

	staticRouter(router)

	r := utils.NewResource(router.Group(""))
	// api 路由
	api := r.Group("api")
	route.SetApiRouter(api)

	return router
}

// 前端静态页面导航
func staticRouter(router *gin.Engine) {
	path := GetAppPath()
	router.StaticFile("/web", filepath.Join(path, "./dist/index.html"))
	router.Static("/assets", filepath.Join(path, "./dist/assets"))
	router.Static("/uploads", filepath.Join(path, "./uploads"))
	router.StaticFile("/"+global.App.Config.App.FaviconName, filepath.Join(path, global.App.Config.App.FaviconPath+"/"+global.App.Config.App.FaviconName))

	router.NoRoute(func(c *gin.Context) {
		web := "http://localhost:5173"
		if gin.Mode() != "release" {
			rep, err := http.Get(web)
			if err == nil {
				// 开发环境
				defer rep.Body.Close()

				vite, err := url.Parse(web)
				if err != nil {
					panic(err)
				}

				// 反向代理到vite页面
				proxy := httputil.NewSingleHostReverseProxy(vite)
				proxy.Director = func(req *http.Request) {
					req.Header = c.Request.Header
					req.Host = vite.Host
					req.URL.Scheme = vite.Scheme
					req.URL.Host = vite.Host
					req.URL.Path = c.Request.URL.Path
				}

				proxy.ServeHTTP(c.Writer, c.Request)
				return
			}
		}
		// 生产环境 重定向到前端页面
		c.Request.URL.Path = "/web"
		router.HandleContext(c)
	})
}

// 启动服务器
func RunServer() {
	r := setupRouter()

	r.Run(global.App.Config.App.Host + ":" + global.App.Config.App.Port)
}
